<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="90px"
    >
      <el-form-item label="关键字" prop="searchValue">
        <el-input
          v-model="queryParams.searchValue"
          placeholder="请输入关键字进行搜索"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="渠道类型" prop="channelType">
        <el-select
          v-model="queryParams.channelType"
          placeholder="请选择渠道类型"
          clearable
          @change="handleQuery"
        >
          <el-option
            v-for="dict in dict.type.distribution_channel_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="渠道等级" prop="levels">
        <el-select
          v-model="queryParams.levels"
          placeholder="请选择渠道等级"
          clearable
          @change="handleQuery"
        >
          <el-option
            v-for="dict in dict.type.agent_level"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker
          v-model="createTime"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          @change="handleQuery"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb-8">
      <el-col :span="1.5" v-hasPermi="['channel:channel:add']">
        <el-button
          v-if="!(userInfo.userType === 1 && userInfo.channelLevels == 3)"
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd(userInfo.userType === 1 ? {id: userInfo.channelId, levels: userInfo.channelLevels} : undefined)"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-sort"
          size="mini"
          @click="toggleExpandAll"
          >展开/折叠</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['channel:channel:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-if="refreshTable"
      v-loading="loading"
      :data="channelList"
      row-key="id"
      :default-expand-all="isExpandAll"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
    >
      <el-table-column label="渠道名称" prop="dname" width="250" fixed="left" />
      <el-table-column label="渠道等级" align="center" prop="levels">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.distribution_level"
            :value="scope.row.levels"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="下级渠道数量"
        align="center"
        prop="channelCount"
      />
      <el-table-column
        label="入驻单位数量"
        align="center"
        prop="companyCount"
      />
      <!-- <el-table-column label="采购设备总数" align="center" prop="aaa" />
      <el-table-column label="已分配" align="center" prop="aaa" />
      <el-table-column label="已激活" align="center" prop="aaa" /> -->
      <el-table-column
        label="渠道商详细地址"
        align="center"
        prop="address"
        width="180"
      />
      <el-table-column label="联系人" align="center" prop="contacts" />
      <el-table-column
        label="联系电话"
        align="center"
        prop="phone"
        width="120"
      />
      <el-table-column label="云豆余额" align="center" prop="balance" />
      <el-table-column label="单位证件" align="center" prop="img1" width="100">
        <template slot-scope="scope">
          <image-preview
            v-if="scope.row.img1"
            :src="scope.row.img1"
            :width="50"
            :height="50"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="更新时间"
        align="center"
        prop="updateTime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updateTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        width="120px"
        fixed="right"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['channel:channel:edit']"
            >修改</el-button
          >
          <el-button
            v-if="scope.row.levels < 3 && hasPermiAnd(['channel:channel:add'])"
            size="mini"
            type="text"
            icon="el-icon-plus"
            @click="handleAdd(scope.row)"

            >新增</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改渠道管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        :show-message="false"
        label-width="100px"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="渠道名称" prop="dname" required>
              <el-input v-model="form.dname" placeholder="请输入渠道名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系人姓名" prop="contacts" required>
              <el-input
                v-model="form.contacts"
                placeholder="请输入联系人姓名"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别" prop="honorific" required>
              <el-radio-group v-model="form.honorific">
                <el-radio
                  v-for="dict in dict.type.sys_user_sex"
                  :key="dict.value"
                  :label="dict.value"
                  >{{ dict.label }}</el-radio
                >
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号码" prop="phone" required>
              <el-input
                v-model="form.phone"
                :maxlength="11"
                placeholder="请输入手机号码"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="渠道类型" prop="channelType" required>
              <el-select
                v-model="form.channelType"
                placeholder="请选择渠道类型"
                style="width: 100%"
              >
                <el-option
                  v-for="dict in dict.type.distribution_channel_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12">
            <el-form-item label="渠道级别" prop="levels" required>
              <el-select
                v-model="form.levels"
                placeholder="请选择渠道级别"
                @change="changeLevels"
                style="width: 100%"
              >
                <el-option
                  v-for="dict in dict.type.distribution_level"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="上级渠道" prop="pid">
              <treeselect
                v-model="form.pid"
                :options="channelOptions"
                :normalizer="normalizer"
                :flat="true"
                placeholder="请选择上级渠道"
              />
            </el-form-item>
          </el-col> -->
          <el-col :span="12">
            <el-form-item label="微信账号" prop="wechatAccount">
              <el-input
                v-model="form.wechatAccount"
                placeholder="请输入微信账号"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="省/市/区">
              <div class="disFlxAC">
                <el-cascader
                  v-if="open && !mapOpen"
                  style="width: 100%"
                  :options="options"
                  :props="props"
                  v-model="areaList"
                  @change="changeAreaList"
                  required
                ></el-cascader>
                <div
                  @click="mapOpen = true"
                  style="width: 60px"
                  class="disFlxCC colorZS"
                >
                  <i class="iconfont el-icon-location fz-28" />
                </div>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="详细地址" prop="address">
              <el-input v-model="form.address" placeholder="请输入详细地址" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="开通后台" prop="" class="ma-0">
              <span>开通</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="抽成比例" prop="channelDraw">
              <div class="disFlx">
                <el-input-number
                  :precision="0"
                  v-model="form.channelDraw"
                  placeholder="请输入"
                  :min="0"
                  :max="100"
                  :disabled="form.id && form.id === userInfo.channelId"
                />
                <span class="pl-2">%</span>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单位证件" prop="img1" class="ma-0">
              <ImageUpload v-model="form.img1" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="备注" prop="remark" class="ma-0">
              <el-input
                v-model="form.remark"
                type="textarea"
                :rows="7"
                placeholder="请输入备注"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <mapDialog :visible.sync="mapOpen" @handelAddress="locationSure" />
  </div>
</template>

<script>
import {
  listChannel,
  getChannel,
  delChannel,
  addChannel,
  updateChannel,
} from "@/api/channel/channel";
import { listArea } from "@/api/saas/area";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import mapDialog from "../../../components/IbsAmap/mapDialog.vue";
import ImageUpload from "@/components/ImageUpload";
import { cloneDeep } from "lodash";
import { hasPermiAnd } from '@/plugins/auth'

export default {
  name: "Channel",
  dicts: [
    "distribution_level",
    "agency_type",
    "agent_level",
    "sys_user_sex",
    "distribution_channel_type",
  ],
  components: {
    Treeselect,
    mapDialog,
    ImageUpload,
  },
  computed: {
    userInfo() {
      return this.$store.state.user.userInfo;
    },
  },
  data() {
    const that = this;
    return {
      // 省市区级联
      options: [],
      props: {
        label: "name",
        value: "id",
        lazy: true,
        lazyLoad(node, resolve) {
          let clevel = node.level + 1;
          console.log(node, clevel, "监听省市区变化");
          listArea({ pid: node.value, level: clevel }).then((res) => {
            if (clevel === 3) {
              res.data.forEach((v) => {
                that.$set(v, "leaf", true);
              });
              if (!res.data) {
                this.form.distincts = "";
              }
            }
            resolve(res.data);
          });
        },
      },
      areaList: [],
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 渠道管理表格数据
      channelList: [],
      // 渠道管理树选项
      channelOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否展开，默认全部展开
      isExpandAll: false,
      // 重新渲染表格状态
      refreshTable: true,
      createTime: "",
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        searchValue: null,
        createTimeStart: null,
        createTimeEnd: null,
        dname: null,
        levels: null,
        contacts: null,
        phone: null,
        adminacc: null,
        adminpass: null,
        img1: "",
        province: null,
        city: null,
        distincts: null,
        address: null,
        proportion: null,
        status: null,
        clientNum: null,
        loginTime: null,
        honorific: null,
        wechatAccount: null,
        openBackstage: null,
        channelType: null,
        balance: null,
        pid: null,
      },
      oldChannelList: [], // 渠道初始数据
      // 表单参数
      form: {
        phone: "",
      },
      // 表单校验
      rules: {},
      mapOpen: false, // 打开地图选择
    };
  },
  created() {
    this.getList();
  },
  activated() {
    this.getList();
  },
  methods: {
    hasPermiAnd,
    // 省市区选择
    changeAreaList(e) {
      console.log(e, "省市区选择");
      e.forEach((item, index) => {
        if (index === 0) {
          this.form.province = item;
          this.form.city = "";
          this.form.distincts = "";
        }
        if (index === 1) {
          this.form.city = item;
          this.form.distincts = "";
        }
        if (index === 2) {
          this.form.distincts = item;
        }
      });
    },
    /** 查询渠道管理列表 */
    getList() {
      this.queryParams.createTimeStart = this.createTime && this.createTime.length ? this.createTime[0] : "";
      this.queryParams.createTimeEnd = this.createTime && this.createTime.length ? this.createTime[1] : "";
      this.loading = true;
      listChannel(this.queryParams).then((response) => {
        response.data = response.data.filter((v) => v.levels != 0); // 去除平台
        this.channelList = this.handleTree(response.data, "id", "pid");
      }).finally(()=>{
        this.loading = false;
      })
    },
    /** 转换渠道管理数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.dname,
        children: node.children,
      };
    },
    /** 查询渠道管理下拉树结构 */
    getTreeselect() {
      listChannel().then((response) => {
        this.oldChannelList = response.data;
        this.changeLevels();
      });
    },
    // 级别变化,获取可操作的渠道树
    changeLevels(val) {
      let levelChannelList = cloneDeep(this.oldChannelList);
      levelChannelList = levelChannelList.filter((v) => {
        if (this.form.levels > v.levels && v.levels != 0) {
          return v;
        }
      });
      const data = { id: 0, dname: "顶级节点", children: [] };
      data.children = this.handleTree(
        levelChannelList,
        "id",
        "pid",
        "children"
      );
      this.channelOptions = [data];
      if (val) {
        this.form.pid = 0;
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        dname: null,
        levels: null,
        contacts: null,
        phone: null,
        adminacc: null,
        adminpass: null,
        img1: "",
        province: null,
        city: null,
        distincts: null,
        address: null,
        proportion: null,
        status: "0",
        clientNum: null,
        loginTime: null,
        createTime: null,
        updateTime: null,
        honorific: "0",
        wechatAccount: null,
        openBackstage: null,
        channelType: null,
        balance: null,
        pid: null,
        channelDraw: null,
      };
      this.areaList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.createTime = "";
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset();

      this.form.pid = row && row.id ? row.id : 0;
      this.form.levels = row && row.id ? `${parseInt(row.levels) + 1}` : "1";
      console.log(JSON.parse(JSON.stringify(this.form)));

      this.title = "添加渠道管理";
      this.getTreeselect();
      this.open = true;
    },
    /** 展开/折叠操作 */
    toggleExpandAll() {
      this.refreshTable = false;
      this.isExpandAll = !this.isExpandAll;
      this.$nextTick(() => {
        this.refreshTable = true;
      });
    },
    /** 修改按钮操作 */
    async handleUpdate(row) {
      this.reset();
      if (row != null) {
        this.form.pid = row.id;
      }
      getChannel(row.id).then((response) => {
        this.form = response.data;
        this.form.channelDraw ? this.form.channelDraw : 0;
        this.form.province ? this.areaList.push(this.form.province) : "";
        this.form.city ? this.areaList.push(this.form.city) : "";
        this.form.distincts ? this.areaList.push(this.form.distincts) : "";
        this.getTreeselect();
        this.open = true;
        this.title = "修改渠道管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      console.log(this.form, "提交表单");
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateChannel(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addChannel(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal
        .confirm('是否确认删除渠道管理编号为"' + row.id + '"的数据项？')
        .then(function () {
          return delChannel(row.id);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "channel/channel/export",
        {
          ...this.queryParams,
        },
        `渠道列表_${this.parseTime(new Date(), "{y}-{m}-{d}")}.xlsx`
      );
    },
    locationSure(e) {
      this.areaList = e.areaList;
      this.changeAreaList(e.areaList);
      this.form.address = e.address;
      console.log(e, "地图选点", this.form);
    },
  },
};
</script>
